/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.tenant.api.handler;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import lombok.Getter;
import lombok.Setter;

/**
 * 多租户上下文过滤器
 *
 * @author zeng
 */
@Setter
@Getter
public class TenantContextFilter implements Filter {
  /** 默认租户标识常量。 在系统中代表默认租户的标识符，通常用于在多租户系统中作为缺省值。 */
  public static final String DEFAULT_TENANT = "0";

  private TenantReader tenantReader = new DefaultTenantReader();

  private String defaultTenantValue = DEFAULT_TENANT;

  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
      throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    try {
      String tenantId = getTenantReader().reader(request);
      TenantRequestContext.setTenantLocal(tenantId);
      chain.doFilter(request, servletResponse);
    } finally {
      TenantRequestContext.remove();
    }
  }
}
